const router = require('koa-router')()
const jwt = require('jsonwebtoken')

router.prefix('/api')

router.post('/login', async (ctx, next) => {
  try {
    const { username, password } = ctx.request.body
    const flag = db.users.some(
      (v) => v.username == username && v.password == password
    )
    const userInfo = db.users.find((v) => v.username == username)
    const token = jwt.sing({ ...userInfo, password: '' }, '2009A', {
      expiresIn: '24h',
    })
    if (flag) {
      ctx.body = {
        code: 0,
        msg: 'success',
        data: token,
      }
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      mag: error,
    }
  }
})

module.exports = router
